<template>
  <view class="group-info-container">
    <!-- 内容区域 -->
    <scroll-view class="content-area" scroll-y>
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 群信息 -->
      <view v-else class="group-content">
        <!-- 群统计信息 -->
        <view class="stats-section">
          <view class="stats-grid">
            <view class="stat-item">
              <text class="stat-number">{{ groupStats.memberCount || 0 }}</text>
              <text class="stat-label">人员总数</text>
            </view>
            <view class="stat-item">
              <text class="stat-number">{{ groupStats.dailyActiveUsers || 0 }}</text>
              <text class="stat-label">日访问量</text>
            </view>
          </view>
        </view>

        <!-- 群成员信息 -->
        <view class="members-section">
          <view class="section-header">
            <text class="section-title">群成员</text>
          </view>

          <!-- 成员头像列表 -->
          <view class="members-grid">
            <view
              v-for="member in displayMembers"
              :key="member.user_id"
              class="member-item"
            >
              <image
                v-if="member.user && member.user.avatar_url"
                :src="member.user.avatar_url"
                class="member-avatar"
                mode="aspectFill"
                @error="handleImageError"
              />
              <view v-else class="member-avatar-placeholder">
                <text class="avatar-text">{{ getMemberInitial(member.user ? member.user.nickname : '') }}</text>
              </view>
            </view>

            <!-- 显示更多按钮 -->
            <view
              v-if="hasMoreMembers"
              class="member-item more-members"
              @click="loadMoreMembers"
            >
              <view class="member-avatar-placeholder more-avatar">
                <text class="avatar-text">+{{ remainingMembersCount }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 群公告 -->
        <view class="announcement-section">
          <view class="section-header">
            <text class="section-title">群公告</text>
          </view>
          
          <view class="announcement-content">
            <view v-if="groupInfo.description && groupInfo.description.trim()" class="announcement-text">
              <text>{{ groupInfo.description }}</text>
            </view>
            <view v-else class="no-announcement">
              <text class="no-announcement-icon">📢</text>
              <text class="no-announcement-text">暂无群公告</text>
              <text class="no-announcement-desc">管理员还没有设置群公告</text>
            </view>
          </view>

          <!-- 更新时间 -->
          <view v-if="groupInfo.created_at" class="update-time">
            <text>更新时间：{{ formatTime(groupInfo.created_at) }}</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { chatAPI, utils } from '@/utils/api.js'

// 响应式数据
const loading = ref(true)
const groupInfo = ref({})
const groupStats = ref({})
const members = ref([])
const membersPage = ref(1)
const membersPageSize = ref(20)
const hasMoreMembers = ref(false)

// 路由参数
const groupId = ref('')

// 计算属性
const displayMembers = computed(() => {
  return members.value.slice(0, 30) // 最多显示30个成员头像
})

const remainingMembersCount = computed(() => {
  const total = groupStats.value.memberCount || 0
  const displayed = Math.min(members.value.length, 30)
  return Math.max(0, total - displayed)
})

// 生命周期 - 获取页面参数
onLoad((options) => {
  groupId.value = options.groupId || ''
  
  if (!groupId.value) {
    uni.showToast({
      title: '群组ID不能为空',
      icon: 'none'
    })
    loading.value = false
    return
  }
})

// 页面加载
onMounted(async () => {
  // 如果没有groupId，不执行后续操作
  if (!groupId.value) {
    return
  }

  try {
    await loadGroupInfo()
    await loadGroupStats()
    await loadMembers()
  } catch (error) {
    console.error('页面初始化失败:', error)
    utils.handleError(error, '页面加载失败')
  } finally {
    loading.value = false
  }
})

/**
 * 加载群组信息
 */
const loadGroupInfo = async () => {
  try {
    if (groupId.value === 'all') {
      // 全国总群模式，设置特殊信息
      groupInfo.value = {
        group_name: '全国总群',
        description: '这里汇聚了所有群组的消息，让您一览全局动态。您可以通过群组选择器切换到具体群组进行交流。',
        created_at: new Date().toISOString()
      }
    } else {
      // 具体群组模式，获取群组详情
      const result = await chatAPI.getGroupDetail(groupId.value)
      if (result.success) {
        groupInfo.value = result.data
      } else {
        throw new Error(result.message || '获取群组信息失败')
      }
    }
  } catch (error) {
    console.error('获取群组信息失败:', error)
    throw error
  }
}

/**
 * 加载群组统计信息
 */
const loadGroupStats = async () => {
  try {
    let result
    if (groupId.value === 'all') {
      // 全国总群模式，获取所有群组汇总统计
      result = await chatAPI.getAllGroupsStats()
    } else {
      // 具体群组模式，获取单个群组统计
      result = await chatAPI.getGroupStats(groupId.value)
    }

    if (result.success) {
      groupStats.value = result.data
    } else {
      throw new Error(result.message || '获取群组统计失败')
    }
  } catch (error) {
    console.error('获取群组统计失败:', error)
    // 不抛出错误，允许页面继续显示
    groupStats.value = {
      memberCount: 0,
      dailyActiveUsers: 0
    }
  }
}

/**
 * 加载群成员
 */
const loadMembers = async () => {
  try {
    let result
    if (groupId.value === 'all') {
      // 全国总群模式，获取所有群组的去重成员
      result = await chatAPI.getAllGroupsMembers(membersPage.value, membersPageSize.value)
    } else {
      // 具体群组模式，获取单个群组成员
      result = await chatAPI.getGroupMembers(groupId.value, membersPage.value, membersPageSize.value)
    }

    if (result.success && result.data.data) {
      members.value = [...members.value, ...result.data.data]
      hasMoreMembers.value = result.data.pagination.hasMore || false
    }
  } catch (error) {
    console.error('获取群成员失败:', error)
    // 不抛出错误，允许页面继续显示
  }
}

/**
 * 加载更多成员
 */
const loadMoreMembers = async () => {
  if (!hasMoreMembers.value) return
  
  membersPage.value++
  await loadMembers()
}

/**
 * 获取成员名称首字母
 */
const getMemberInitial = (nickname) => {
  if (!nickname) return '用'
  return nickname.charAt(0).toUpperCase()
}

/**
 * 处理图片加载错误
 */
const handleImageError = (e) => {
  console.log('头像加载失败:', e)
}

/**
 * 格式化时间
 */
const formatTime = (timeStr) => {
  const time = new Date(timeStr)
  const year = time.getFullYear()
  const month = time.getMonth() + 1
  const day = time.getDate()
  return `${year}年${month}月${day}日`
}


</script>

<style scoped>
.group-info-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}



/* 内容区域 */
.content-area {
  flex: 1;
  padding: 20rpx;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

/* 群信息内容 */
.group-content {
  display: flex;
  flex-direction: column;
  gap: 30rpx;
}

/* 通用区块样式 */
.stats-section,
.members-section,
.announcement-section {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.section-header {
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

/* 统计信息样式 */
.stats-grid {
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-number {
  font-size: 48rpx;
  font-weight: bold;
  color: #007AFF;
  margin-bottom: 8rpx;
}

.stat-label {
  font-size: 26rpx;
  color: #666;
}

/* 成员网格 */
.members-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.member-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 80rpx;
}

.member-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.member-avatar-placeholder {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.more-avatar {
  background: #f0f0f0;
  border: 2rpx dashed #ccc;
}

.avatar-text {
  font-size: 24rpx;
  color: #666;
  font-weight: 500;
}

.more-members {
  cursor: pointer;
}

/* 群公告 */
.announcement-content {
  min-height: 120rpx;
}

.announcement-text {
  line-height: 1.6;
}

.announcement-text text {
  font-size: 28rpx;
  color: #333;
}

.no-announcement {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;
}

.no-announcement-icon {
  font-size: 60rpx;
  margin-bottom: 16rpx;
}

.no-announcement-text {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.no-announcement-desc {
  font-size: 24rpx;
  color: #999;
}

.update-time {
  margin-top: 20rpx;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.update-time text {
  font-size: 24rpx;
  color: #999;
}
</style>
